/*
 * BanBu_MyFriendViewController
 * @description 本文件提供通讯录界面（包括好友关注粉丝）的ViewController
 * @package
 * @author 		***
 * @copyright
 * @version 		1.0
 * @description 本文件提供通讯录界面（包括好友关注粉丝）的ViewController
 */

#import "BanBu_MyFriendViewController.h"
#import "BanBu_ListCell.h"
#import "BanBu_PersonDataViewController.h"
#import "BanBu_AddNewFriendViewController.h"
#import "AppDataManager.h"
#import "AppCommunicationManager.h"
#import "TKLoadingView.h"
#import "LeveyTabBarController.h"
#import "BanBu_NavButton.h"
#import "BanBu_ImageView.h"
#import "BanBu_FriendTypeListViewController.h"
#import "CJSONSerializer.h"
#import "CJSONDeserializer.h"

@interface BanBu_MyFriendViewController ()

@end

@implementation BanBu_MyFriendViewController

@synthesize listType = _listType;
//@synthesize currentPage = _currentPage;
@synthesize typeString = _typeString;
@synthesize number=_number;


- (void)viewDidLoad
{
    [super viewDidLoad];
//    [self setRefreshing];
    alreadyRefresh = YES;
    isLoading      = NO;
//    self.tableView.frame = CGRectMake(0, 25, __MainScreen_Width, 50);
    //    summary = [[NSDictionary alloc]init];
    moreView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 80)];
    lab = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, 320,20)];
    lab.font= [UIFont systemFontOfSize:15];
    lab.backgroundColor =[UIColor colorWithRed:254.0/255.0 green:250.0/255.0 blue:239.0/255.0 alpha:1];
    lab.textAlignment = kTextAlignmentCenter;
    lab.textColor = [UIColor grayColor];
    lab.backgroundColor = [UIColor clearColor];
    [moreView addSubview:lab];
    
    loadingView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    loadingView.hidden = NO;
    [loadingView setHidesWhenStopped:YES];
    loadingView.frame = CGRectMake(0, 0, 50, 50);
    loadingView.center = CGPointMake(160-([NSLocalizedString(@"loadingNotice", nil) sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(320, 20) lineBreakMode:kTextLineBreakByWordWrapping].width/2)-15, 20);
    moreView.backgroundColor = [UIColor clearColor];
    [moreView addSubview:loadingView];
    [loadingView release];
    
    cacheArray = [[NSMutableArray alloc] initWithCapacity:20];
    
    requestArr = [[NSMutableArray alloc]initWithCapacity:10];
    deleteArr = [[NSMutableArray alloc] init];
    
    self.navigationItem.title = @"";
    
    self.tableView.backgroundColor = [UIColor colorWithRed:255.0/255 green:250.0/255 blue:240.0/255 alpha:1.0];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    BanBu_ImageView *imggg= [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable]autorelease];
    self.tableView.backgroundView = imggg;
    //    NSLog(@"%f",backX);
    NSDictionary *defaultSum = [[UserDefaults valueForKey:MyAppDataManager.useruid]valueForKey:@"friendsum"];
//    NSLog(@"%@",[UserDefaults valueForKey:MyAppDataManager.useruid]);
//    NSLog(@"%@",defaultSum);
//    NSLog(@"%@",defaultSum);
    if(defaultSum)
    {
        summary = [[NSDictionary alloc]initWithDictionary:defaultSum];
    }
    NSString *defaultTitle;
    
    
    if(summary.count){
        defaultTitle = [NSString stringWithFormat:@"%@(%@)",NSLocalizedString(@"summary_h", nil),[summary objectForKey:@"h"]];
    }else{
        defaultTitle = [NSString stringWithFormat:@"%@(0)",NSLocalizedString(@"summary_h", nil)];
        
    }
    backX = [defaultTitle sizeWithFont:[UIFont boldSystemFontOfSize:22] constrainedToSize:CGSizeMake(200, 44)].width+20+16;

    UIView *centerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 260, 44)];
    categoryButton = [UIButton buttonWithType:UIButtonTypeCustom];
    categoryButton.frame = CGRectMake(150-backX/2, 0, backX, 44);
    [categoryButton addTarget:self action:@selector(categoryAction:) forControlEvents:UIControlEventTouchUpInside];
    [categoryButton setTitleEdgeInsets:UIEdgeInsetsMake(3, 2, 2, 2)];
    
//    NSArray *friend = [NSArray arrayWithArray:[[summary objectForKey:@"h"] componentsSeparatedByString:@","]];
    
    [categoryButton setTitle:[NSString stringWithFormat:@"%@(%@)",NSLocalizedString(@"summary_h", nil),[summary valueForKey:@"h"]] forState:UIControlStateNormal];
    categoryButton.titleLabel.font = [UIFont boldSystemFontOfSize:18];
    [centerView addSubview:categoryButton];
    laImageView = [[UIImageView alloc]initWithFrame:CGRectMake(categoryButton.frame.origin.x + backX - 16, 15, 16, 16)];
    laImageView.image = [UIImage imageNamed:@"down.png"];
   
    [centerView addSubview:laImageView];
    [laImageView release];
    self.navigationItem.titleView = centerView;
//    self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:centerView] autorelease];
    [centerView release];
    
    BanBu_NavButton *addButton = [[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal];
    addButton.position = ButtonPositionRight;
    addButton.frame = CGRectMake(0, 0, 40, 30);
    [addButton addTarget:self action:@selector(addFriend:) forControlEvents:UIControlEventTouchUpInside];
    [addButton setImage:[UIImage imageNamed:@"btn_plus.png"] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:addButton] autorelease];
    [addButton release];
    
    _listType = 0;
    NSString *friendListPath = [DataCachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@-hlistdata",MyAppDataManager.useruid]];
    [MyAppDataManager.friends addObjectsFromArray:[NSKeyedUnarchiver unarchiveObjectWithData:[NSData dataWithContentsOfFile:friendListPath]]];
    
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    
}
//坑人代码
-(void)rotateImageView{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    CGAffineTransform transform = CGAffineTransformRotate(laImageView.transform, -M_PI);
    laImageView.transform = transform;
    [UIView commitAnimations];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    BanBu_SmallListView *listView = (BanBu_SmallListView *)[self.navigationController.view viewWithTag:102];
    if(listView){
        [listView dismissWithAnimation:YES];
        [self rotateImageView];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.leveyTabBarController hidesTabBar:NO animated:YES];
    
    if((!MyAppDataManager.friends.count||!_currentPage)&&!_isLoadingRefresh)
    {
        [self setRefreshing];
        return;
    }
     
}

- (void)dealloc
{
    [lab release],lab= nil;
    [moreView release];moreView = nil;
    [self.tableView removeObserver:self forKeyPath:@"contentOffset"];
    [super dealloc];
    
}



- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - 点击出现通讯录选择界面
-(void)categoryAction:(UIButton *)button
{
    BanBu_SmallListView *listView = (BanBu_SmallListView *)[self.navigationController.view viewWithTag:102];
    if(listView)
    {
        [self rotateImageView];
        [listView dismissWithAnimation:YES];
        return;
    }
    [self rotateImageView];
    NSArray *titles;
    if(summary.count){
        titles = [NSArray arrayWithObjects:[NSString stringWithFormat:@"%@(%@)",NSLocalizedString(@"summary_h", nil),[summary valueForKey:@"h"]],[NSString stringWithFormat:@"%@(%@)",NSLocalizedString(@"summary_g", nil),[summary valueForKey:@"g"]],[NSString stringWithFormat:@"%@(%@)",NSLocalizedString(@"summary_f", nil),[summary valueForKey:@"f"]],nil];

    }else{
        titles = [NSArray arrayWithObjects:[NSString stringWithFormat:@"%@(0)",NSLocalizedString(@"summary_h", nil)],[NSString stringWithFormat:@"%@(0)",NSLocalizedString(@"summary_g", nil)],[NSString stringWithFormat:@"%@(0)",NSLocalizedString(@"summary_f", nil)],nil];
        
    }
    BanBu_SmallListView *smallList = [[BanBu_SmallListView alloc] initWithFrame:CGRectMake(0, 130.0-backX/2, 200.0, 150) listTitles:titles];
    smallList.tag = 102;
    smallList.delegate = self;
    smallList.selectedIndex = _listType;
    [smallList showFromPoint:CGPointMake(60, self.navigationController.view.frame.size.height-(__MainScreen_Height-44)) inView:self.navigationController.view animation:YES];
    [smallList release];

}

#pragma mark - 从各平台邀请好友
- (void)addFriend:(UIButton *)button
{
    BanBu_FriendTypeListViewController * friend = [[BanBu_FriendTypeListViewController alloc]init];
    [self.leveyTabBarController hidesTabBar:YES animated:YES];
    [self.navigationController pushViewController:friend animated:YES];
    [friend release];
    friend = nil;
//    BanBu_AddNewFriendViewController *addNew = [[BanBu_AddNewFriendViewController alloc] init];
//    [self.leveyTabBarController hidesTabBar:YES animated:YES];
//    [self.navigationController pushViewController:addNew animated:YES];
//    [addNew release];
}


#pragma mark - 切换好友，粉丝和关注
#pragma mark small listview delegate
- (void)smallListView:(BanBu_SmallListView *)smallListView didSelectIndex:(NSInteger)index
{
    
    if([self.view viewWithTag:100]){
        [[self.view viewWithTag:100]removeFromSuperview];
        [[self.view viewWithTag:101]removeFromSuperview];
    }
    
    NSArray *titles;
    if(summary.count){
        titles = [NSArray arrayWithObjects:[NSString stringWithFormat:@"%@(%@)",NSLocalizedString(@"summary_h", nil),[summary valueForKey:@"h"]],[NSString stringWithFormat:@"%@(%@)",NSLocalizedString(@"summary_g", nil),[summary valueForKey:@"g"]],[NSString stringWithFormat:@"%@(%@)",NSLocalizedString(@"summary_f", nil),[summary valueForKey:@"f"]],nil];
    }else{
        titles = [NSArray arrayWithObjects:[NSString stringWithFormat:@"%@(0)",NSLocalizedString(@"summary_h", nil)],[NSString stringWithFormat:@"%@(0)",NSLocalizedString(@"summary_g", nil)],[NSString stringWithFormat:@"%@(0)",NSLocalizedString(@"summary_f", nil)],nil];
        
    }
    [smallListView dismissWithAnimation:YES];
    
    //记录选择的类型
    _listType = index;
    [categoryButton setTitle:[titles objectAtIndex:_listType] forState:UIControlStateNormal];
    
    backX = [[titles objectAtIndex:_listType] sizeWithFont:[UIFont boldSystemFontOfSize:22] constrainedToSize:CGSizeMake(200, 44)].width+20+16;
    categoryButton.frame = CGRectMake(150-backX/2, 0, backX, 44);
    laImageView.frame = CGRectMake(categoryButton.frame.origin.x+backX-16, 15, 16, 16);
    [self setRefreshing];
}


- (void)loadingData
{
    BanBu_SmallListView *listView = (BanBu_SmallListView *)[self.navigationController.view viewWithTag:102];
    if(listView)
    {
        [listView dismissWithAnimation:YES];
        [self rotateImageView];
    }
    if([self.view viewWithTag:100]){
        [[self.view viewWithTag:100]removeFromSuperview];
        [[self.view viewWithTag:101]removeFromSuperview];
    }
    if(_isLoadingRefresh)
    {
        _currentPage = 1;
    }
    else if(_currentPage ==1)
    {
        _currentPage = 3;
    }
    else
        _currentPage ++;
    [AppComManager cancalHandlesForObject:self];
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    NSArray *guanxi = [NSArray arrayWithObjects:@"h",@"g",@"f", nil];
    [parDic setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
    [parDic setValue:[guanxi objectAtIndex:_listType] forKey:@"linkkind"];
    [parDic setValue:[NSString stringWithFormat:@"%i",_currentPage] forKey:PageNo];
    [AppComManager getBanBuData:BanBu_Get_Friend_OfMy par:parDic delegate:self];

}



//好友圈数据返回：ok  = y 当所有好友刷新完后继续刷新依然返回y 但是返回数据列表为空，当返回为空时禁止继续拉动刷新更多，只能通过下拉刷新后才能继续上拉刷新；
- (void)banbuRequestDidFinished:(NSDictionary *)resDic error:(NSError *)error
{
    NSLog(@"%@",resDic);
    self.navigationController.view.userInteractionEnabled = YES;
    [TKLoadingView dismissTkFromView:self.view animated:YES afterShow:0.0];
    if(error)
    {
        [TKLoadingView showTkloadingAddedTo:self.view title:NSLocalizedString(@"network_error", nil) activityAnimated:NO duration:2.0];
        lab.text = NSLocalizedString(@"network_error", nil);
        {
            lab.text = NSLocalizedString(@"noData", nil);
        }
        //        alreadyRefresh = YES;
        if(_currentPage>3)
        {
            _currentPage--;
        }
        else
        {
            _currentPage =1;
        }
        [self finishedLoading];
        return;
    }
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init]autorelease];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    if([[resDic valueForKey:@"servertime"] length])
    {
        MyAppDataManager.timeDifference = [[formatter dateFromString:[NSString stringWithFormat:@"%@",[resDic valueForKey:@"servertime"]]] timeIntervalSinceNow];
        [UserDefaults setObject:[NSNumber numberWithDouble:MyAppDataManager.timeDifference] forKey:@"timedifference"];
    }
    else
    {
        MyAppDataManager.timeDifference = [[UserDefaults valueForKey:@"timedifference"] doubleValue];
    }
    
    if([AppComManager respondsDic:resDic isFunctionData:BanBu_Get_Friend_OfMy]){
        if([[resDic valueForKey:@"ok"]boolValue]){
            if(_isLoadingRefresh)
            {
                //对名字和话，进行替换后，在存储
                [MyAppDataManager.friends removeAllObjects];
                [cacheArray removeAllObjects];
                for(int i=0;i<[[resDic valueForKey:@"list"]count];i++){
                    NSMutableDictionary *aDic = [NSMutableDictionary dictionaryWithDictionary:[[resDic valueForKey:@"list"] objectAtIndex:i]];
                    if([MyAppDataManager theRevisedName:[[aDic valueForKey:@"userinfor"] valueForKey:@"pname"] andUID:[aDic valueForKey:@"userid"]])
                    {
                        NSMutableDictionary *userinfor = [[NSMutableDictionary alloc] initWithDictionary:[aDic valueForKey:@"userinfor"]];
                        [userinfor setObject:[MyAppDataManager theRevisedName:[userinfor valueForKey:@"pname"] andUID:[aDic valueForKey:@"userid"]] forKey:@"pname"];
                        [aDic setObject:userinfor forKey:@"userinfor"];
                        [userinfor release];
                    }
                    if(i<20)
                        [MyAppDataManager.friends addObject:aDic];
                    else
                        [cacheArray addObject:aDic];
                }
                NSMutableDictionary *uidDic = [NSMutableDictionary dictionaryWithDictionary:[UserDefaults valueForKey:MyAppDataManager.useruid]];
                [uidDic setValue:[resDic valueForKey:@"friendlist"] forKey:FriendShip];
//                NSLog(@"%@",resDic);
                [uidDic setValue:[resDic valueForKey:@"friendsum"] forKey:@"friendsum"];
                [UserDefaults setValue:uidDic forKey:MyAppDataManager.useruid];
                [UserDefaults synchronize];

                summary = [[NSDictionary alloc]initWithDictionary:[resDic objectForKey:@"friendsum"]];
                //++++++
                NSArray *titles;
                if(summary.count){
                    NSArray *guanxi = [NSArray arrayWithObjects:@"h",@"g",@"f", nil];
                    numberOfFriends = [[summary valueForKey:[guanxi objectAtIndex:_listType]] integerValue];//记录当前下得最高刷新数目
                    
                    titles = [NSArray arrayWithObjects:[NSString stringWithFormat:@"%@(%@)",NSLocalizedString(@"summary_h", nil),[summary valueForKey:@"h"]],[NSString stringWithFormat:@"%@(%@)",NSLocalizedString(@"summary_g", nil),[summary valueForKey:@"g"]],[NSString stringWithFormat:@"%@(%@)",NSLocalizedString(@"summary_f", nil),[summary valueForKey:@"f"]],nil];

                }else{
                    titles = [NSArray arrayWithObjects:[NSString stringWithFormat:@"%@(0)",NSLocalizedString(@"summary_h", nil)],[NSString stringWithFormat:@"%@(0)",NSLocalizedString(@"summary_g", nil)],[NSString stringWithFormat:@"%@(0)",NSLocalizedString(@"summary_f", nil)],nil];
                    numberOfFriends = 0;
                    
                }
//                backX = [[NSString stringWithFormat:@"%@(%@)",NSLocalizedString(@"summary_h", nil),[summary valueForKey:@"h"]] sizeWithFont:[UIFont boldSystemFontOfSize:22] constrainedToSize:CGSizeMake(200, 44)].width+20+16;
//                
//                categoryButton.frame = CGRectMake(150-backX/2, 0, backX, 44);
//                [laImageView setFrame:CGRectMake(categoryButton.frame.origin.x + backX - 16, 15, 16, 16)];
               
                [categoryButton setTitle:[titles objectAtIndex:_listType] forState:UIControlStateNormal];
                
                //++++++
                if([MyAppDataManager.friends count]==0){
                    numberOfFriends = 0;
                    if(cryImageView || noticeLabel){
                        [[self.view viewWithTag:100]removeFromSuperview];
                        [[self.view viewWithTag:101]removeFromSuperview];
                    }
                    cryImageView = [[UIImageView alloc]initWithFrame:CGRectMake(136, 100, 48, 48)];
                    cryImageView.image = [UIImage imageNamed:@"cry.png"];
                    cryImageView.tag= 100;
                    [self.tableView addSubview:cryImageView];
                    [cryImageView release];
                    noticeLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 150, 300, 100)];
                    noticeLabel.tag = 101;
                    noticeLabel.numberOfLines = 0;
                    NSArray *noticeArray = [NSArray arrayWithObjects:NSLocalizedString(@"friendNoticeLabel2", nil),NSLocalizedString(@"friendNoticeLabel", nil),NSLocalizedString(@"friendNoticeLabel1", nil), nil];
                    noticeLabel.text = [noticeArray objectAtIndex:_listType];
                    noticeLabel.font = [UIFont systemFontOfSize:16];
                    noticeLabel.textAlignment = kTextAlignmentCenter;
                    noticeLabel.backgroundColor = [UIColor clearColor];
                    noticeLabel.textColor = [UIColor darkGrayColor];
                    [self.tableView addSubview:noticeLabel];
                    self.tableView.tableFooterView = nil;
                    [noticeLabel release];
                    
                    self.tableView.scrollEnabled = NO;
                }
                else
                {
                    self.tableView.scrollEnabled = YES;
                    self.tableView.tableFooterView = moreView;
                    [self.tableView addObserver:self forKeyPath:@"contentOffset" options:NSKeyValueObservingOptionNew context:self.tableView];
                    
                }
                
            }
            else
            {
                //对名字和话，进行替换后，在存储
                for(int i=0;i<[[resDic valueForKey:@"list"]count];i++){
                    NSMutableDictionary *aDic = [NSMutableDictionary dictionaryWithDictionary:[[resDic valueForKey:@"list"] objectAtIndex:i]];
                    if([MyAppDataManager theRevisedName:[aDic valueForKey:@"pname"] andUID:[aDic valueForKey:@"userid"]]){
                        [aDic setObject:[MyAppDataManager theRevisedName:[aDic valueForKey:@"pname"] andUID:[aDic valueForKey:@"userid"]] forKey:@"pname"];
                    }
                    [cacheArray addObject:aDic];
                }
                                
                if(!alreadyRefresh&&isLoading&&cacheArray.count)
                {
                    [self startLoadNextPage];
                    [self loadingData];
                }
                if(!cacheArray.count)
                {
                    [loadingView stopAnimating];
                    if(_currentPage>3)
                    {
                        _currentPage--;
                    }
                    else
                    {
                        _currentPage =1;
                    }
                    lab.text = NSLocalizedString(@"noData", nil);
                    return;
                }
                
            }

            //2014年08月18日10:07:30，程序在下面这句闪退，不清楚原因，隐藏，发现没问题
//            __block typeof(MyAppDataManager)blockDataManager = MyAppDataManager;
//            dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//            dispatch_async(queue, ^{
//                NSData *listData = [NSKeyedArchiver archivedDataWithRootObject:blockDataManager.friends];
//                NSArray *guanxi = [NSArray arrayWithObjects:@"h",@"g",@"f", nil];
//                NSString *path = [DataCachePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@-%@listdata",MyAppDataManager.useruid,[guanxi objectAtIndex:_listType]]];
//                [listData writeToFile:path atomically:YES];
//            });
        }
        else
        {
            if(_currentPage>3)
            {
                _currentPage--;
            }
            else
            {
                _currentPage =1;
            }
            if(!alreadyRefresh&&isLoading)
            {
                
                [loadingView stopAnimating];
                //                alreadyRefresh = YES;
                lab.text = NSLocalizedString(@"noData", nil);
            }
        }
    }
    isLoading = NO;
    
    [self.tableView reloadData];
    [self finishedLoading];
    
    //NSLog(@"rrrr:%@",MyAppDataManager.friends);
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return MyAppDataManager.friends.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
	
    return 84;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ListCellIdentifier = @"ListCellIdentifier";
    BanBu_ListCell *cell = (BanBu_ListCell *)[tableView dequeueReusableCellWithIdentifier:ListCellIdentifier];
    if(cell == nil)
    {
        cell = [[[BanBu_ListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ListCellIdentifier] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    }
    if(MyAppDataManager.friends.count){
        NSDictionary *buddy = [MyAppDataManager.friends objectAtIndex:indexPath.row];
        [cell updateListCell:buddy];
    }
    
    return cell;
}


#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *aFriend = [MyAppDataManager.friends objectAtIndex:indexPath.row];
    BanBu_PersonDataViewController *peopleFfofile = [[BanBu_PersonDataViewController alloc] initWithProfile:[aFriend valueForKey:keyPersonalInfo]];
    [self.leveyTabBarController hidesTabBar:YES animated:YES];
    [self.navigationController pushViewController:peopleFfofile animated:YES];
    [peopleFfofile release];
}

-(void)tableView:(UITableView *)tableView didEndDisplayingCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    if(cell){
        [(BanBu_ListCell*)cell cancelImageLoad];
        //        self.tableView.frame = CGRectMake(0,0,320,__MainScreen_Height-44-50);
        
    }
}


-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    
//    NSLog(@"%@",NSStringFromCGRect(self.tableView.frame));
//    if(indexPath.row == MyAppDataManager.friends.count-1&&alreadyRefresh)
//    {
//        self.tableView.frame = CGRectMake(0,0,320,__MainScreen_Height-90);
//        
//    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [UIView setAnimationsEnabled:YES];
    [super viewWillAppear:animated];
}
-(void)startLoadNextPage
{
    if(cacheArray.count)
    {
        
        [MyAppDataManager.friends addObjectsFromArray:cacheArray];
        [cacheArray removeAllObjects];
//        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[MyAppDataManager.friends count] - 1 inSection:0];
        [UIView animateWithDuration:0.5 animations:^{
            [self.tableView reloadData];
//            [self.tableView scrollToRowAtIndexPath:indexPath atScrollPosition:UITableViewScrollPositionBottom animated:YES];
        }];
        alreadyRefresh = YES;
        [loadingView stopAnimating];
    }
    if(!cacheArray.count)
    {
        [self loadingData];
        isLoading = YES;
    }
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if([keyPath isEqual:@"contentOffset"])
    {
        if(self.tableView.contentOffset.y>self.tableView.contentSize.height-__MainScreen_Height+44+48)
        {
            if(!isLoading&&!_isLoadingRefresh&&MyAppDataManager.friends.count<numberOfFriends)
            {
                alreadyRefresh = NO;
                _isLoadingRefresh = NO;
                [loadingView startAnimating];
                lab.text = NSLocalizedString(@"loadingNotice", nil);
                self.tableView.tableFooterView = moreView;
                isLoading = YES;
                [self performSelector:@selector(startLoadNextPage) withObject:nil afterDelay:0.5];
            }
        }
    }
}

@end
